package com.jyw.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.EventBusTypes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.util.ConvertUtils;
import cn.qqtheme.framework.widget.WheelView;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/2
 */

public class AddressAddActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout layoutCitySelect;
    private EditText editCircle, editDetail, editName, editPhone;
    private ImageView ivLocation, ivFemale, ivMale;
    private TextView tvCity, btnGo;

    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();

    private boolean isFemale = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_add);

        layoutCitySelect = (LinearLayout) findViewById(R.id.layout_city_select);
        findViewById(R.id.iv_back).setOnClickListener(this);
        editCircle = (EditText) findViewById(R.id.edit_circle);
        editDetail = (EditText) findViewById(R.id.edit_detail);
        editName = (EditText) findViewById(R.id.edit_name);
        editPhone = (EditText) findViewById(R.id.edit_phone);
        ivLocation = (ImageView) findViewById(R.id.iv_location);
        ivFemale = (ImageView) findViewById(R.id.iv_female);
        ivMale = (ImageView) findViewById(R.id.iv_male);
        tvCity = (TextView) findViewById(R.id.tv_city);
        btnGo = (TextView) findViewById(R.id.btn_go);

        ivLocation.setOnClickListener(this);
        layoutCitySelect.setOnClickListener(this);
        btnGo.setOnClickListener(this);
        ivFemale.setOnClickListener(this);
        ivMale.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_city_select:
                new AddressInitTask(this).execute("河南", "安阳", "文峰");
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_location:
                mLocationClient = new LocationClient(AddressAddActivity.this);
                mLocationClient.registerLocationListener(myListener);

                setLocationOption();
                mLocationClient.start();
                break;
            case R.id.btn_go:
                if (!isValidated()) {
                    break;
                } else {
                    go();
                }
                break;
            case R.id.iv_female:
                ivFemale.setImageResource(R.drawable.address_select);
                ivMale.setImageResource(R.drawable.address_normal);
                isFemale = true;
                break;
            case R.id.iv_male:
                ivFemale.setImageResource(R.drawable.address_normal);
                ivMale.setImageResource(R.drawable.address_select);
                isFemale = false;
                break;
        }
    }

    private void go() {
        Request request = new Request.Builder().
                url(Server.ADD_ADDRESS + "?login_phone_data=" + getPrefs().getString("phone", "")
                        + "&city_data=" + tvCity.getText().toString()
                        + "&circle_data=" + editCircle.getText().toString()
                        + "&detail_data=" + editDetail.getText().toString()
                        + "&name_data=" + editName.getText().toString()
                        + "&sex_data=" + (isFemale ? "0" : "1")
                        + "&phone_data=" + editPhone.getText().toString()
                        + "&id_data="
                ).build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(AddressAddActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                EventBus.getDefault().post(new EventBusTypes.AddressAdded());
                finish();
            }
        });
    }

    private boolean isValidated() {
        if (tvCity.getText().toString().equals("")) {
            Toast.makeText(AddressAddActivity.this, "省市区选择不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (editCircle.getText().toString().equals("")) {
            Toast.makeText(AddressAddActivity.this, "小区或大厦名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (editDetail.getText().toString().equals("")) {
            Toast.makeText(AddressAddActivity.this, "门牌号或详细地址不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (editName.getText().toString().equals("")) {
            Toast.makeText(AddressAddActivity.this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (editPhone.getText().toString().equals("")) {
            Toast.makeText(AddressAddActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        Pattern p1 = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
        if (!p1.matcher(editPhone.getText().toString()).matches()) {
            Toast.makeText(AddressAddActivity.this, "手机号有误", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }


    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getBuildingName() == null) {
                editCircle.setText(location.getStreet());
            } else {
                editCircle.setText(location.getStreet() + "," + location.getBuildingName());
            }
            mLocationClient.stop();
        }
    }


    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); //打开gps
        option.setServiceName("com.baidu.location.service_v2.9");
        /*option.setPoiExtraInfo(true);*/
        option.setAddrType("all");
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setPriority(LocationClientOption.GpsFirst);       //gps
        /*option.setPoiNumber(10);*/
        option.disableCache(true);
        mLocationClient.setLocOption(option);
    }


    class AddressInitTask extends AsyncTask<String, Void, ArrayList<Province>> {
        private Activity activity;
        private ProgressDialog dialog;
        private String selectedProvince = "", selectedCity = "", selectedCounty = "";
        private boolean hideCounty = false;

        /**
         * 初始化为不显示区县的模式
         */
        public AddressInitTask(Activity activity, boolean hideCounty) {
            this.activity = activity;
            this.hideCounty = hideCounty;
            dialog = ProgressDialog.show(activity, null, "正在初始化数据...", true, true);
        }

        public AddressInitTask(Activity activity) {
            this.activity = activity;
            dialog = ProgressDialog.show(activity, null, "正在初始化数据...", true, true);
        }

        @Override
        protected ArrayList<Province> doInBackground(String... params) {
            if (params != null) {
                switch (params.length) {
                    case 1:
                        selectedProvince = params[0];
                        break;
                    case 2:
                        selectedProvince = params[0];
                        selectedCity = params[1];
                        break;
                    case 3:
                        selectedProvince = params[0];
                        selectedCity = params[1];
                        selectedCounty = params[2];
                        break;
                    default:
                        break;
                }
            }
            ArrayList<Province> data = new ArrayList<Province>();
            try {
                String json = ConvertUtils.toString(activity.getAssets().open("city.json"));
                data.addAll(JSON.parseArray(json, Province.class));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }

        @Override
        protected void onPostExecute(ArrayList<Province> result) {
            dialog.dismiss();
            if (result.size() > 0) {
                AddressPicker picker = new AddressPicker(activity, result);
                picker.setHideCounty(hideCounty);
                if (hideCounty) {
                    picker.setColumnWeight(1 / 3.0, 2 / 3.0);//将屏幕分为3份，省级和地级的比例为1:2
                } else {
                    picker.setColumnWeight(2 / 8.0, 3 / 8.0, 3 / 8.0);//省级、地级和县级的比例为2:3:3
                }
                picker.setSelectedItem(selectedProvince, selectedCity, selectedCounty);
                picker.setLineConfig(new WheelView.LineConfig(0));//使用最长的分割线
                picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() {
                    @Override
                    public void onAddressPicked(Province province, City city, County county) {
                        tvCity.setText(province.getAreaName() + "," + city.getAreaName() + "," + county.getAreaName());
                    }
                });
                picker.show();
            } else {
                Toast.makeText(activity, "AddressPicker数据初始化失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

}
